<template>
  <s-layout title="抢红包">
    <view class="lottery-container">

      <div class="lottery_box">
        <image
          class="bgi"
          src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250310/decdbff88245eae45872f82d23bc707e_pay.png"
          mode="widthFix"
        ></image>
        <!-- 九宫格抢红包区域 -->
        <view class="lottery-grid">
          <template v-for="(item, index) in display_prizes" :key="index">
            <view :class="['lottery-item', { active: current_index === item.original_index }]">
              <template v-if="item.is_center">
                <view class="start-btn-wrap" @click="start_lottery">
                  <view class="start-btn">开始抢红包</view>
                </view>
              </template>
              <template v-else>
                <image :src="item.image || ''" class="prize-img"></image>
                <view class="prize-name">{{ item.name }}</view>
              </template>
            </view>
          </template>
        </view>
      </div>

      <!-- 规则说明 -->
      <!-- <view class="lottery-rules">
      <view class="rules-title">活动规则</view>
      <view class="rules-content">
        <view v-for="(rule, index) in rules_list" :key="index" class="rule-item">
          {{ index + 1 }}. {{ rule }}
        </view>
      </view>
    </view> -->

      <!-- 中奖弹窗 -->
      <view class="prize-popup" v-if="show_result">
        <view class="popup-content">
          <view class="popup-title">抢红包结果</view>
          <view class="popup-prize">{{ win_prize.name }}</view>
          <image :src="win_prize.image || ''" class="popup-img"></image>
          <view class="popup-btn" @click="close_popup(win_prize.name)">确定</view>
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import sheep from '@/sheep';

  // 状态定义
  const state = reactive({
    prize_list: [],
  });

  const chance_count = ref(3);
  const is_center_button = ref(true);
  const current_index = ref(-1);
  const is_running = ref(false);
  const win_prize = ref({});
  const show_result = ref(false);

  // 活动规则
  const rules_list = reactive([
    '每位用户默认拥有1次抢红包机会',
    '活动时间：2023年8月1日至2023年8月31日',
    '中奖后请在7天内联系客服领取奖品',
    '本活动最终解释权归本公司所有',
  ]);

  //开奖

  // 计算属性
  const display_prizes = computed(() => {
    return state.prize_list.map((item, index) => ({
      ...item,
      is_center: index === 4,
      original_index: index,
    }));
  });

  // 方法定义
  // 开始抢红包
  const start_lottery = async () => {
    // 检查是否有抢红包机会
    // if (chance_count.value <= 0) {
    //   uni.showToast({
    //     title: '抢红包机会已用完',
    //     icon: 'none',
    //   });
    //   return;
    // }

    // 检查是否正在抢红包中
    if (is_running.value) {
      return;
    }

    is_running.value = true;
    chance_count.value--;

    // 模拟抢红包过程
    let run_times = 0;
    let run_count = 30 + Math.floor(Math.random() * 10); // 至少转30圈
    let speed = 80; // 初始速度
    let prize_id = await get_prize_index(); // 获取中奖ID

    // 找到奖品在列表中的实际位置
    const prizeIndex = state.prize_list.findIndex((item) => item.id === prize_id);
    if (prizeIndex === -1) {
      console.error('未找到对应奖品');
      is_running.value=false
      return;
    }

    console.log('中奖位置:', prizeIndex, '奖品ID:', prize_id);

    // 计算显示位置（考虑中间按钮的影响）
    let display_index = prizeIndex;
    // 修正索引映射逻辑
    // if (prizeIndex >= 4) {
    //   display_index = prizeIndex; // 移除 +1 操作
    // }

    // 找到对应的动画序列位置
    const target_position = lottery_index_order.indexOf(display_index);
    console.log('奖品ID:', prize_id, '列表位置:', prizeIndex, '目标位置:', target_position);

    // 确保目标位置有效
    if (target_position === -1) {
      console.error('无效的目标位置');
      return;
    }
    console.log('目标位置:', target_position, '显示索引:', display_index);

    // 抢红包动画
    let timer = null;
    const runLottery = () => {
      run_times++;

      // 当前高亮位置
      const position = run_times % lottery_index_order.length;
      current_index.value = lottery_index_order[position];

      // 根据转动次数调整速度
      if (run_times > run_count - 10) {
        speed = 300;
      } else if (run_times > run_count - 20) {
        speed = 200;
      } else if (run_times > run_count / 2) {
        speed = 150;
      } else {
        speed = 100;
      }

      // 停止条件（确保完全匹配目标位置）
      if (run_times >= run_count && position === target_position) {
        clearTimeout(timer);
        is_running.value = false;
        show_lottery_result(prize_id);
        return;
      }

      timer = setTimeout(runLottery, speed);
    };

    // 开始动画
    timer = setTimeout(runLottery, speed);
  };

  // 获取中奖索引
  const get_prize_index = async () => {
    let res = await sheep.$api.tuangou.open({id:2});
    console.log(res);
    if (res.error == 0) {
      return res.data.id;
    }
  };

  // 显示抢红包结果
  const show_lottery_result = (index) => {
    // 直接使用接口返回的索引查找奖品
    const prize = state.prize_list.find((item) => item.id === index);
    if (prize) {
      win_prize.value = prize;
    } else {
      console.error('未找到对应奖品:', index);
    }

    setTimeout(() => {
      show_result.value = true;
    }, 500);
  };

  // 关闭弹窗
  const close_popup = async (name) => {
    show_result.value = false;
    current_index.value = -1;

    if (name !== '谢谢惠顾') {
      await sheep.$store('user').getInfo();
      sheep.$router.go('/pages/user/wallet/money');
    }
  };

  // 设置奖品列表
  const set_prize_list = (list) => {
    if (list && list.length === 8) {
      const new_list = [...list];
      new_list.splice(4, 0, {
        id: 5,
        name: '开始',
        probability: 0,
        image: '',
      });
      state.prize_list.splice(0, state.prize_list.length, ...new_list);
    }
  };

  // 设置规则列表
  const set_rules_list = (rules) => {
    if (rules && rules.length > 0) {
      rules_list.splice(0, rules_list.length, ...rules);
    }
  };

  // 设置抢红包机会
  const set_chance_count = (count) => {
    chance_count.value = count;
  };

  // 获取奖品列表
  const get_prize_list = async () => {
    const res = await sheep.$api.tuangou.poolDetail({id:2});
    state.prize_list = res.data;
  };

  // 生命周期
  onLoad(() => {
    // 获取奖品列表
    get_prize_list();
  });

  // 九宫格索引顺序
  const lottery_index_order = reactive([0, 1, 2, 5, 8, 7, 6, 3]);
</script>

<style lang="less">
  .lottery_box {
    width: 100%;
    height: 100vh;
    position: relative;

    .bgi {
      width: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }

    .lottery-grid {
      position: absolute;
      top: 310rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 550rpx;
      height: 550rpx;
    }
  }

  .lottery-container {
    // padding: 30rpx;
    // background-color: #fff;
    min-height: 100vh;

    // 标题样式
    .lottery-title {
      font-size: 40rpx;
      font-weight: bold;
      text-align: center;
      color: #ff4500;
      margin-bottom: 20rpx;
    }

    // 抢红包机会样式
    .lottery-chance {
      text-align: center;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 30rpx;
    }

    // 九宫格样式
    .lottery-grid {
      margin: 0 auto;
      //   background-color: #fe8848;
      border-radius: 20rpx;
      padding: 15rpx;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-template-rows: repeat(3, 1fr);
      gap: 15rpx;

      // 单个奖品格子
      .lottery-item {
        background-color: #fefbe6;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        position: relative;
        height: 100%;
        width: 100%;
        box-sizing: border-box;
        overflow: hidden;

        &.active {
          background-color: #ff9d00;
          transform: scale(0.95);
        }

        // 奖品图片
        .prize-img {
          width: 100rpx;
          height: 100rpx;
          margin-bottom: 10rpx;
          background-color: #f5f5f5;
        }

        // 奖品名称
        .prize-name {
          font-size: 24rpx;
          color: #ff3c47;
          text-align: center;
        }

        // 开始按钮包装
        .start-btn-wrap {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: #ff4500;
          position: relative;
          cursor: pointer;

          &::after {
            content: '';
            position: absolute;
            left: 50%;
            bottom: 0;
            transform: translateX(-50%);
            width: 0;
            height: 0;
            border-left: 120rpx solid transparent;
            border-right: 120rpx solid transparent;
            border-bottom: 60rpx solid #ff6600;
          }

          // 开始按钮文字
          .start-btn {
            color: #fff;
            font-size: 32rpx;
            font-weight: bold;
            z-index: 1;
            position: relative;
            top: -10rpx;
          }
        }
      }
    }

    // 规则样式
    .lottery-rules {
      margin-top: 40rpx;
      padding: 30rpx 0;

      .rules-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 20rpx;
      }

      .rules-content {
        .rule-item {
          font-size: 26rpx;
          color: #666;
          line-height: 1.8;
        }
      }
    }

    // 中奖弹窗
    .prize-popup {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.6);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 999;

      .popup-content {
        width: 500rpx;
        background-color: #fff;
        border-radius: 20rpx;
        padding: 40rpx;
        display: flex;
        flex-direction: column;
        align-items: center;

        .popup-title {
          font-size: 32rpx;
          color: #333;
          margin-bottom: 20rpx;
        }

        .popup-prize {
          font-size: 40rpx;
          font-weight: bold;
          color: #ff6600;
          margin-bottom: 30rpx;
        }

        .popup-img {
          width: 200rpx;
          height: 200rpx;
          margin-bottom: 30rpx;
          background-color: #f0f0f0;
        }

        .popup-btn {
          width: 200rpx;
          height: 80rpx;
          background-color: #ff6600;
          color: #fff;
          border-radius: 40rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 28rpx;
        }
      }
    }
  }
</style>
